package com.example.springboottest.example.trywithresource;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * try-with-resources 可以自动关闭实现了 AutoCloseable 和 Closeable 接口的资源，不用在finally里面手动关闭
 * <p>
 * try-catch-finally则不行，需要在finally里面关闭，同时还需要考虑finally抛出异常，需要在finally里面继续try-catch
 */
public class TryWithResource {
    static int n;
    static byte[] buff = new byte[1024];

    public static void main(String[] args) {
//        tryCatch();

//        tryWithResource();

        tryWithResource2();
    }

    /**
     * 使用try-catch块异常处理代码
     */
    public static void tryCatch() {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("/Users/fangdaye/work/workspace/spring-boot-test/src/main/java/com/example/springboottest/example/trywithresource/file.txt");
            while ((n = fileInputStream.read(buff)) != -1) {
                System.out.write(buff, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用try-with-resources块改进异常处理代码
     */
    public static void tryWithResource() {
        try (FileInputStream fileInputStream = new FileInputStream("/Users/fangdaye/work/workspace/spring-boot-test/src/main/java/com/example/springboottest/example/trywithresource/file.txt")) {
            while ((n = fileInputStream.read(buff)) != -1) {
                System.out.write(buff, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * jdk9再次优化
     * try()里面可以直接只写变量
     */
    public static void tryWithResourceJDK9() throws FileNotFoundException {
//        FileInputStream fileInputStream = new FileInputStream("/Users/fangdaye/work/workspace/spring-boot-test/src/main/java/com/example/springboottest/example/trywithresource/file.txt");
//
//        try (fileInputStream) {
//            while ((n = fileInputStream.read(buff)) != -1) {
//                System.out.write(buff, 0, n);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    public static void tryWithResource2() {
        try (MyResource myResource = new MyResource()) {
            System.out.println("执行with语句");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("执行完毕");
    }
}
